package com.Cychat.post.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class WebSocketNotificationService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送通知消息给指定用户
     * 
     * @param receiverId   接收者ID
     * @param senderId     发送者ID
     * @param content      消息内容
     * @param senderName   发送者名称
     * @param senderAvatar 发送者头像
     * @param postId       帖子ID（可选）
     */
    public void sendNotificationMessage(Long receiverId, Long senderId, String content,
            String senderName, String senderAvatar, Integer postId) {
        try {
            // 构造消息内容
            Map<String, Object> message = new HashMap<>();
            message.put("id", System.currentTimeMillis() + "");
            message.put("toId", receiverId.toString());
            message.put("fromId", senderId.toString());
            message.put("name", senderName != null ? senderName : "互动消息");
            message.put("headImg", senderAvatar != null ? senderAvatar
                    : "https://pet-java-chengdu-123.oss-cn-chengdu.aliyuncs.com/%E7%94%9F%E6%88%90%E5%AE%98%E6%96%B9%E7%8C%AB%E7%8B%97%20logo.png");
            message.put("msg", content);
            message.put("time", new java.util.Date().toString());
            message.put("type", "send");
            message.put("messageType", "notification");
            // 添加action字段来标识是互动消息
            message.put("action", "interaction");

            // 如果有帖子ID，也一并发送
            if (postId != null) {
                message.put("postId", postId);
            }

            // 发送到chat服务 - 使用服务发现名称
            String chatServiceUrl = "http://Cychat-Java-chat/api/chat/sendNotification";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(message, headers);

            // 发送POST请求
            restTemplate.postForObject(chatServiceUrl, request, String.class);

            System.out.println("WebSocket推送结果: 成功 - 接收者ID: " + receiverId + ", 内容: " + content);
        } catch (Exception e) {
            System.err.println("WebSocket推送结果: 失败 - 接收者ID: " + receiverId + ", 错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}